<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="80%" max-height="65vh" scroll>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="auto"
      v-loading="formLoading"
      :disabled="isDisabled"
    >
      <el-tabs v-model="activeTab" type="border-card">
        <el-tab-pane label="基本信息" name="1">
          <!-- 藏品关键信息 -->
          <el-card class="field-group" shadow="never">
            <template #header>
              <div class="field-group-header">
                <span class="field-group-title">藏品关键信息</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="藏品总登记号" prop="generalAccessionNumber">
                  <el-input v-model="formData.generalAccessionNumber" placeholder="请输入藏品总登记号" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="藏品名称" prop="collectionName">
                  <el-input v-model="formData.collectionName" placeholder="请输入藏品名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="数量" prop="collectionNum">
                  <el-input v-model="formData.collectionNum" placeholder="请输入数量" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <!-- 加工成果数据信息 -->
          <el-card class="field-group" shadow="never">
            <template #header>
              <div class="field-group-header">
                <span class="field-group-title">加工成果数据信息</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="成果名称" prop="resultName">
                  <el-input v-model="formData.resultName" placeholder="请输入成果名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="文件格式" prop="fileFormat">
                  <el-input v-model="formData.fileFormat" placeholder="请输入文件格式" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="加工日期" prop="processingDate">
                  <el-date-picker
                    v-model="formData.processingDate"
                    type="date"
                    value-format="x"
                    placeholder="选择加工日期"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="加工单位" prop="processingUnit">
                  <el-input v-model="formData.processingUnit" placeholder="请输入加工单位" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="加工人" prop="processor">
                  <el-input v-model="formData.processor" placeholder="请输入加工人" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="加工成果质量检查人" prop="qualityInspector">
                  <el-input
                    v-model="formData.qualityInspector"
                    placeholder="请输入加工成果质量检查人"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="贴图分辨率(dpi)" prop="textureResolution">
                  <el-input
                    v-model="formData.textureResolution"
                    placeholder="请输入贴图分辨率(dpi)"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <!-- 三维扫描点云数据采集 -->
          <el-card class="field-group" shadow="never">
            <template #header>
              <div class="field-group-header">
                <span class="field-group-title">三维扫描点云数据采集</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="采集单位" prop="scanAcquisitionUnit">
                  <el-input v-model="formData.scanAcquisitionUnit" placeholder="请输入采集单位" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="采集地点" prop="scanAcquisitionLocation">
                  <el-input v-model="formData.scanAcquisitionLocation" placeholder="请输入采集地点" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="采集日期" prop="scanAcquisitionDate">
                  <el-date-picker
                    v-model="formData.scanAcquisitionDate"
                    type="date"
                    value-format="x"
                    placeholder="选择采集日期"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="采集人员" prop="scanAcquisitionPersonnel">
                  <el-input v-model="formData.scanAcquisitionPersonnel" placeholder="请输入采集人员" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="采集设备品牌型号" prop="scanEquipmentModel">
                  <el-input v-model="formData.scanEquipmentModel" placeholder="请输入采集设备品牌型号" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="文件格式" prop="scanFileFormat">
                  <el-input v-model="formData.scanFileFormat" placeholder="请输入文件格式" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="模型精度(mm)" prop="scanModelAccuracy">
                  <el-input v-model="formData.scanModelAccuracy" placeholder="请输入模型精度(mm)" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="采集质量检查人" prop="scanAcquisitionInspector">
                  <el-input
                    v-model="formData.scanAcquisitionInspector"
                    placeholder="请输入采集质量检查人"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <!-- 摄影测量纹理数据采集 -->
          <el-card class="field-group" shadow="never">
            <template #header>
              <div class="field-group-header">
                <span class="field-group-title">摄影测量纹理数据采集</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="采集单位" prop="photoAcquisitionUnit">
                  <el-input v-model="formData.photoAcquisitionUnit" placeholder="请输入采集单位" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="采集地点" prop="photoAcquisitionLocation">
                  <el-input v-model="formData.photoAcquisitionLocation" placeholder="请输入采集地点" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="采集日期" prop="photoAcquisitionDate">
                  <el-date-picker
                    v-model="formData.photoAcquisitionDate"
                    type="date"
                    value-format="x"
                    placeholder="选择采集日期"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="采集人员" prop="photoAcquisitionPersonnel">
                  <el-input v-model="formData.photoAcquisitionPersonnel" placeholder="请输入采集人员" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="采集设备品牌型号" prop="photoEquipmentModel">
                  <el-input v-model="formData.photoEquipmentModel" placeholder="请输入采集设备品牌型号" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="文件格式" prop="photoFileFormat">
                  <el-input v-model="formData.photoFileFormat" placeholder="请输入文件格式" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="采集影像总数(张)" prop="totalImages">
                  <el-input v-model="formData.totalImages" placeholder="请输入采集影像总数(张)" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="采集质量检查人" prop="photoAcquisitionInspector">
                  <el-input
                    v-model="formData.photoAcquisitionInspector"
                    placeholder="请输入采集质量检查人"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="分辨率(dpi)" prop="resolution">
                  <el-input v-model="formData.resolution" placeholder="请输入分辨率(dpi)" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-tab-pane>

        <!-- 附件tab保持不变 -->
        <el-tab-pane label="附件" name="2">
          <el-row :gutter="20">
            <!-- 0：藏品主图 -->
            <el-col :span="24">
              <el-form-item label="藏品主图" prop="collectionCover">
                <UploadImg
                  v-model="formData.collectionCover"
                  :fileSize="100"
                  :fileType="['jpeg', 'jpg', 'png', 'gif', 'webp']"
                  height="120px"
                  width="120px"
                  @change="(files) => handleFileChange(files, 'images')"
                  :isShowTip="true"
                  :disabled="isDisabled"
                />
              </el-form-item>
            </el-col>

            <!-- 5：链接地址 -->
            <el-col :span="24">
              <el-form-item label="链接地址" prop="collectionLinks">
                <div class="link-input-container">
                  <div
                    v-for="(link, index) in collectionLinks"
                    :key="index"
                    class="link-input-item"
                  >
                    <el-input v-model="link.url" placeholder="请输入链接地址" clearable>
                      <template #prepend>链接{{ index + 1 }}</template>
                      <template #append>
                        <view style="width: 30px">
                          <el-button
                            @click="removeLink(index)"
                            type="danger"
                            size="small"
                            v-if="collectionLinks.length > 1"
                          >
                            <Icon icon="ep:delete" />
                          </el-button>
                        </view>
                        <view>
                          <el-form :disabled="false">
                            <el-button
                              @click="downloadLink(link.url)"
                              :disabled="!link.url"
                              type="primary"
                              size="small"
                            >
                              <Icon icon="ep:download" />
                            </el-button>
                          </el-form>
                        </view>
                      </template>
                    </el-input>
                  </div>
                  <el-button @click="addLink" type="primary" size="small" class="add-link-btn">
                    <Icon icon="ep:plus" /> 添加链接
                  </el-button>
                </div>
                <div class="upload-tip">可添加多个相关链接地址</div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading" v-if="!isDisabled"
      >确 定</el-button
      >
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
// 导入部分保持不变
import {
  Collection3dAcquisitionApi,
  Collection3dAcquisitionVO
} from '@/api/dr/collection3dacquisition'
import { CollectionManagementApi } from '@/api/dr/collectionmanagement'

/** 藏品三维采集信息 表单 */
defineOptions({ name: 'Collection3dAcquisitionForm' })
const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  }
})

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const activeTab = ref('1')
const formType = ref('') // 表单的类型：create - 新增；update - 修改, 'view', 'download'
const formData: any = ref({})
const isDisabled = computed(() => ['view', 'download'].includes(formType.value))

// 多媒体文件数据
const collectionImages = ref<string>('') // 藏品图片
const collectionAudios = ref<string>('') // 藏品音频
const collectionVideos = ref<string>('') // 藏品视频
const collection3DFiles = ref<string>('') // 藏品三维文件
const collection3DPreciseFiles = ref<string>('') // 藏品精准三维文件
// 链接地址数据
const collectionLinks = ref([{ url: '' }]) // 初始化一个空链接

// 表单验证规则 - 根据需要添加新字段的验证
const formRules = reactive({
  collectionId: [{ required: true, message: '关联藏品ID不能为空', trigger: 'blur' }],
  collectionName: [{ required: true, message: '藏品名称不能为空', trigger: 'blur' }],
  generalAccessionNumber: [{ required: true, message: '藏品总登记号不能为空', trigger: 'blur' }]
})

const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await Collection3dAcquisitionApi.getCollection3dAcquisition(id)
      // 获取多媒体文件数据
      loadCollectionMediaFiles(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  // 提交前构建collectionLinkAddress数组
  buildCollectionLinkAddress()
  try {
    const data = formData.value as unknown as Collection3dAcquisitionVO
    if (formType.value === 'create') {
      await Collection3dAcquisitionApi.createCollection3dAcquisition({
        ...data,
        collectionId: props.data.id
      })
      message.success(t('common.createSuccess'))
    } else {
      await Collection3dAcquisitionApi.updateCollection3dAcquisition(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {}
  formRef.value?.resetFields()
}

// 文件名映射 - 存储URL到原始文件名的映射关系
const fileNameMaps = ref({
  images: new Map<string, string>(),
  audios: new Map<string, string>(),
  videos: new Map<string, string>(),
  files3D: new Map<string, string>(),
  preciseFiles3D: new Map<string, string>()
})

// 文件名处理函数
const handleFileChange = (
  files: any[],
  type: 'images' | 'audios' | 'videos' | 'files3D' | 'preciseFiles3D'
) => {
  console.log(`📁 ${type} 文件变化:`, files)
  const fileList = Array.isArray(files) ? files : []

  // 清空旧的映射
  fileNameMaps.value[type].clear()

  // 建立新的URL到文件名映射
  fileList?.forEach((file) => {
    if (file.url && file.name) {
      fileNameMaps.value[type].set(file.url, file.name)
      console.log(`💾 保存文件名映射: ${file.url} -> ${file.name}`)
    }
  })
}

// 链接地址操作函数
const addLink = () => {
  collectionLinks.value.push({ url: '' })
}

const removeLink = (index: number) => {
  if (collectionLinks.value.length > 1) {
    collectionLinks.value.splice(index, 1)
  }
}

const downloadLink = (url: string) => {
  url && window.open(url)
}

// 将各个文件变量转换为统一的collectionLinkAddress数组
const buildCollectionLinkAddress = () => {
  const linkAddresses: any[] = []

  // 0: 藏品主图
  if (formData.value.collectionCover) {
    linkAddresses.push({
      type: 0,
      linkAddress: formData.value.collectionCover,
      fileName: formData.value.collectionCover.substring(
        formData.value.collectionCover.lastIndexOf('/') + 1
      ) // 主图从URL提取文件名
    })
  }

  // 1: 藏品图片 (多个)
  if (collectionImages.value) {
    const images = collectionImages.value.split(',').filter((url) => url.trim())
    images.forEach((url) => {
      const trimmedUrl = url.trim()
      linkAddresses.push({
        type: 1,
        linkAddress: trimmedUrl,
        fileName:
          fileNameMaps.value.images.get(trimmedUrl) ||
          trimmedUrl.substring(trimmedUrl.lastIndexOf('/') + 1)
      })
    })
  }

  // 2: 藏品音频 (多个)
  if (collectionAudios.value) {
    const audios = collectionAudios.value.split(',').filter((url) => url.trim())
    audios.forEach((url) => {
      const trimmedUrl = url.trim()
      linkAddresses.push({
        type: 2,
        linkAddress: trimmedUrl,
        fileName:
          fileNameMaps.value.audios.get(trimmedUrl) ||
          trimmedUrl.substring(trimmedUrl.lastIndexOf('/') + 1)
      })
    })
  }

  // 3: 藏品视频 (多个)
  if (collectionVideos.value) {
    const videos = collectionVideos.value.split(',').filter((url) => url.trim())
    videos.forEach((url) => {
      const trimmedUrl = url.trim()
      linkAddresses.push({
        type: 3,
        linkAddress: trimmedUrl,
        fileName:
          fileNameMaps.value.videos.get(trimmedUrl) ||
          trimmedUrl.substring(trimmedUrl.lastIndexOf('/') + 1)
      })
    })
  }

  // 4: 藏品三维文件 (多个)
  if (collection3DFiles.value) {
    const files3D = collection3DFiles.value.split(',').filter((url) => url.trim())
    files3D.forEach((url) => {
      const trimmedUrl = url.trim()
      linkAddresses.push({
        type: 4,
        linkAddress: trimmedUrl,
        fileName:
          fileNameMaps.value.files3D.get(trimmedUrl) ||
          trimmedUrl.substring(trimmedUrl.lastIndexOf('/') + 1)
      })
    })
  }

  // 5: 链接地址 (多个)
  collectionLinks.value.forEach((link) => {
    if (link.url && link.url.trim()) {
      linkAddresses.push({
        type: 5,
        linkAddress: link.url.trim(),
        fileName: link.url.trim() // 链接地址使用URL本身作为显示名称
      })
    }
  })

  // 6: 藏品精准三维文件 (多个)
  if (collection3DPreciseFiles.value) {
    const preciseFiles3D = collection3DPreciseFiles.value.split(',').filter((url) => url.trim())
    preciseFiles3D.forEach((url) => {
      const trimmedUrl = url.trim()
      linkAddresses.push({
        type: 6,
        linkAddress: trimmedUrl,
        fileName:
          fileNameMaps.value.preciseFiles3D.get(trimmedUrl) ||
          trimmedUrl.substring(trimmedUrl.lastIndexOf('/') + 1)
      })
    })
  }

  formData.value.collectionLinkAddress = linkAddresses
  console.log('🔗 构建的collectionLinkAddress（包含fileName）：', linkAddresses)
}

// 加载藏品多媒体文件数据
const loadCollectionMediaFiles = async (collectionId: number) => {
  try {
    const linkData = await CollectionManagementApi.getCollectionModelLinkAddress({
      collectionId,
      bizType: 3
    })
    console.log('🔗 获取的多媒体数据：', linkData)

    if (linkData && Array.isArray(linkData)) {
      // 清空文件名映射
      Object.keys(fileNameMaps.value).forEach((key) => {
        fileNameMaps.value[key as keyof typeof fileNameMaps.value].clear()
      })

      // 解析返回的数据到各个变量
      const images: string[] = []
      const audios: string[] = []
      const videos: string[] = []
      const files3D: string[] = []
      const preciseFiles3D: string[] = []
      const links: any[] = []

      linkData.forEach((item: any) => {
        console.log(item, 'item')
        // 将type转换为数字进行比较
        const typeNum = parseInt(item.type)
        const url = item.linkAddress
        const fileName = item.fileName || url.substring(url.lastIndexOf('/') + 1)
        console.log('fileName', fileName)

        switch (typeNum) {
          case 0: // 藏品主图
            formData.value.collectionCover = url
            break
          case 1: // 藏品图片
            images.push(url)
            fileNameMaps.value.images.set(url, fileName)
            break
          case 2: // 藏品音频
            audios.push(url)
            fileNameMaps.value.audios.set(url, fileName)
            break
          case 3: // 藏品视频
            videos.push(url)
            fileNameMaps.value.videos.set(url, fileName)
            break
          case 4: // 藏品三维文件
            files3D.push(url)
            fileNameMaps.value.files3D.set(url, fileName)
            break
          case 5: // 链接地址
            links.push({ url: url })
            break
          case 6: // 藏品精准三维文件
            preciseFiles3D.push(url)
            fileNameMaps.value.preciseFiles3D.set(url, fileName)
            break
        }
      })

      // 更新各个ref变量
      collectionImages.value = images.join(',')
      collectionAudios.value = audios.join(',')
      collectionVideos.value = videos.join(',')
      collection3DFiles.value = files3D.join(',')
      collection3DPreciseFiles.value = preciseFiles3D.join(',')
      collectionLinks.value = links.length > 0 ? links : [{ url: '' }]

      console.log('📂 设置的多媒体文件（包含文件名映射）：', {
        cover: formData.value.collectionCover,
        images: collectionImages.value,
        audios: collectionAudios.value,
        videos: collectionVideos.value,
        files3D: collection3DFiles.value,
        preciseFiles3D: collection3DPreciseFiles.value,
        links: collectionLinks.value,
        fileNameMaps: {
          images: Array.from(fileNameMaps.value.images.entries()),
          audios: Array.from(fileNameMaps.value.audios.entries()),
          videos: Array.from(fileNameMaps.value.videos.entries()),
          files3D: Array.from(fileNameMaps.value.files3D.entries()),
          preciseFiles3D: Array.from(fileNameMaps.value.preciseFiles3D.entries())
        }
      })
    }
  } catch (error) {
    console.error('获取多媒体文件失败：', error)
  }
}
</script>

<style lang="scss" scoped>
.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  line-height: 1.4;
}

/* 链接输入框样式 */
.link-input-container {
  width: 100%;
  .link-input-item {
    margin-bottom: 12px;
  }

  .link-input-item:last-child {
    margin-bottom: 0;
  }

  .add-link-btn {
    margin-top: 8px;
  }
}

/* 字段分组样式 */
.field-group {
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;

  &:last-child {
    margin-bottom: 0;
  }

  .field-group-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .field-group-title {
    font-weight: 600;
    color: #303133;
    font-size: 16px;
  }
}

:deep(.el-card__header) {
  padding: 12px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}
</style>
